#include<cstdio>
using namespace std;
const int maxn=1e5;
struct node{
    int next;
    bool flag=false;
}word[maxn];
int main(){
    //freopen("in.txt","r",stdin);
    int me,next,n,astart,bstart;
    char c;
    scanf("%d %d %d",&astart,&bstart,&n);
    for(int i=0;i<n;i++){
        scanf("%d %c %d",&me,&c,&next);
        word[me].next=next;
    }
    while(astart!=-1){
        word[astart].flag=true;
        astart=word[astart].next;
    }
    int mark=-1;
    while(bstart!=-1){
        if(word[bstart].flag==true){mark=bstart;break;}
        bstart=word[bstart].next;
    }
    if(mark==-1){
        printf("-1\n");
    }
    else{
        printf("%05d",mark);
    }
}
